package Offer.offer2022;

/**
 * 顺时针打印矩阵
 */
public class Test20 {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
        printMatrix(matrix);
    }

    public static void printMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }

        int rows = matrix.length;
        int columns = matrix[0].length;

        int start = 0;
        while (rows > 2 * start && columns > 2 * start) {
            printMatrixCircle(matrix, rows, columns, start);
            start++;
        }
    }

    private static void printMatrixCircle(int[][] matrix, int rows, int columns, int start) {
        int endRow = rows - start - 1;
        int endColumn = columns - start - 1;
        //从左到右打印上面的一行
        for (int i = start; i <= endColumn; i++) {
            System.out.print(matrix[start][i]);
            System.out.print(" ");
        }
        //从上到下打印右边的一行
        if (endRow > start) {
            for (int i = start + 1; i <= endRow; i++) {
                System.out.print(matrix[i][endColumn]);
                System.out.print(" ");
            }
        }
        //从右到左打印下面的一行
        if (endRow > start && endColumn > start) {
            for (int i = endColumn - 1; i >= start; i--) {
                System.out.print(matrix[endRow][i]);
                System.out.print(" ");
            }
        }
        //从下到上打印左边的一行
        if (endRow > start + 1 && endColumn > start) {
            for (int i = endRow - 1; i > start; i--) {
                System.out.print(matrix[i][start]);
                System.out.print(" ");
            }
        }
    }
}
